﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Diagnostics;
using System.Windows.Media.Imaging;
using System.IO;
using System.Data;

using ImageTools;
using ImageTools.IO;
using ImageTools.IO.Gif;
using ImageTools.IO.Png;
using ImageTools.IO.Bmp;
using BYRBBS.Model;

namespace BYRForum
{
    public partial class ArticleListItem : UserControl
    {
        /// <summary>
        /// 该控件有一个输入，该输入为ArticleItem，这个类是我在Model里面定义的那个
        /// 从这个输入中可以获取需要的信息，比如作者，发帖时间，标题内容等
        /// 命名为BYRForum.ArticleItem
        /// </summary>
        public ArticleListItem()
        {
            InitializeComponent();
        }



        public ArticleItem ArticleItemData
        {
            get { return (ArticleItem)GetValue(ArticleItemDataProperty); }
            set { SetValue(ArticleItemDataProperty, value); }
        }
        public event RoutedEventHandler ImageClick;
        //1539862628
        // Using a DependencyProperty as the backing store for ArticleItemData.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ArticleItemDataProperty =
            DependencyProperty.Register("ArticleItemData", typeof(ArticleItem), typeof(ArticleListItem), new PropertyMetadata(null, OnDataChanged));

        //当对控件输入AritcleItem参数或者该参数变动时，将会调用该函数
        static void OnDataChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            Decoders.AddDecoder<BmpDecoder>();
            Decoders.AddDecoder<PngDecoder>();
            Decoders.AddDecoder<GifDecoder>();

            ArticleListItem ali = (ArticleListItem)obj;//表示该控件本身
            ArticleItem ad = (ArticleItem)e.NewValue;//为输入的AriticleItem参数，从这个对象中获取具体信息
            if (ad != null)
            {
                Debug.WriteLine(ad.author.Id);
                Debug.WriteLine(ad.Content);
                ali.textblockUserId.Text = ad.author.Id;//对于用户信息、标题、内容等简单信息，可以直接填充到界面上
                ali.textBlockUserName.Text = ad.author.User_name;
                if (ad.author.Face_url != null)
                {

                
                    string[] tmp=ad.author.Face_url.Split('.');
                    Uri faceUri = new Uri(ad.author.Face_url, UriKind.Absolute);//对于用户头像，显示方式类似
                    if (tmp[tmp.Length - 1] == "gif" || tmp[tmp.Length - 1] == "GIF")
                    {
                        ExtendedImage image = new ExtendedImage();
                        image.UriSource = faceUri;
                        ali.imageUser.Source = image;
                        ali.imageUserJpg.Source = null;
                    }
                    else
                    {
                        BitmapImage bmp = new BitmapImage();
                        bmp.UriSource = faceUri;
                        ali.imageUserJpg.Source = bmp;
                        ali.imageUser.Source = null;
                    }

                }
                
                

                ali.textblockTitle.Text = ad.Title;
                if (ad.Position == "0")
                    ali.PositionTextBlock.Text = "楼主";
                else
                    ali.PositionTextBlock.Text = ad.Position + "楼";
                


                DateTime dtStart = new DateTime(1970, 1, 1);//这是发帖时间格式转换
                long lTime = long.Parse(ad.Post_time + "0000000");
                TimeSpan toNow = new TimeSpan(lTime);
                DateTime dtResult = dtStart.Add(toNow);


                ali.textblockInfo.Text = "发表于" + dtResult.ToString("yyyy-MM-dd HH:mm:ss"); ;
                ali.ContentStackPanel.Children.Clear();
                ScrewText(ali, ad.Content);//如果贴子中的文字过多将会使用该函数将文字在多个textblock中显示

                //当有附件，假设附件为图片，先去请求 图片
                if (ad.Att.Att_file.Length != 0)
                {
                    Debug.WriteLine("attach list count" + ad.Att.Att_file.Length);
                    for (int i = 0; i < ad.Att.Att_file.Length; i++)
                    {
                        Debug.WriteLine(ad.Att.Att_file[i].Thumbnail_middle);
                        try
                        {

                            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(ad.Att.Att_file[i].Thumbnail_middle + ByrApi.appkey);
                            req.Credentials = new NetworkCredential(App.MyInfo.Id, App.MyInfo.Password);
                            RequestState myState = new RequestState();
                            myState.request = req;
                            myState.articleItem = ali;
                            req.BeginGetResponse(HttpWebRequset_Callback, myState);

                        }
                        catch
                        {
                            Debug.WriteLine("network failed");
                        }
                    }
                }
            }
            else
            {

            }

        }
        static void HttpWebRequset_Callback(IAsyncResult asynchronousResult)
        {
            RequestState state = (RequestState)asynchronousResult.AsyncState;
            ArticleListItem ali = (ArticleListItem)state.articleItem;
            HttpWebRequest hwrq = state.request;
            try
            {
                HttpWebResponse response = (HttpWebResponse)hwrq.EndGetResponse(asynchronousResult);
                Debug.WriteLine("get callback");
                Stream responseStream = response.GetResponseStream();
                ali.Dispatcher.BeginInvoke(
                    () =>
                    {
                        //请求道图片后，将图片动态的添加到这个控件的ContentStackPanel这个容器中，也就是直接贴在了后面
                        BitmapImage bmp = new BitmapImage();
                        try
                        {
                            bmp.SetSource(responseStream);
                            Image img = new Image();
                            img.Source = bmp;
                            img.Margin = new Thickness(10, 10, 10, 10);
                            ali.ContentStackPanel.Children.Add(img);
                        }
                        catch (Exception exc)
                        {
                            Debug.WriteLine(exc.Message);
                        }
                    }
                    );
                //response.Close();
                //responseStream.Close();
            }
            catch (Exception ee)
            {
                Debug.WriteLine("image get back failed" + ee.Message);
            }



        }
        static void ScrewText(ArticleListItem ali, string content)
        {
            int sect = (int)(content.Length / 800);
            //ali.ContentStackPanel.Children.Clear();
            TextBlock tb = new TextBlock();

            Debug.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@sect:" + sect + "content length:" + content.Length);
            if (sect == 0)
            {
                tb.Text = content;
                tb.TextWrapping = TextWrapping.Wrap;
                ali.ContentStackPanel.Children.Add(tb);
                return;
            }
            for (int i = 0; i <= sect; i++)
            {
                TextBlock tba = new TextBlock();
                if (i != sect)
                {

                    tba.Text = content.Substring(800 * i, 800);
                    tba.TextWrapping = TextWrapping.Wrap;
                }
                else
                {
                    tba.Text = content.Substring(800 * i);
                    tba.TextWrapping = TextWrapping.Wrap;

                }
                ali.ContentStackPanel.Children.Add(tba);

            }
        }

        private void imageUser_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            Debug.WriteLine("image usr has been clicked_________________________");
            ImageClick(this,new RoutedEventArgs());
            
        }



    }

}
